package com.haoshuang.zhouzhoubang.ui.page.study.child

import android.os.Bundle
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.config.URLConstants
import com.haoshuang.zhouzhoubang.databinding.FragmentStudyChildBinding
import com.haoshuang.zhouzhoubang.model.bean.TrainArticleBean
import com.haoshuang.zhouzhoubang.ui.page.study.detail.TrainDetailsActivity
import com.mufeng.libs.base.BaseVMFragment
import com.mufeng.libs.core.setEmptyData
import com.mufeng.libs.core.setOnItemClick
import com.mufeng.libs.core.setupData
import com.mufeng.libs.core.setupEmptyData
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.vertical

/**
 *  
 */
class StudyChildFragment : BaseVMFragment<StudyChildViewModel, FragmentStudyChildBinding>() {

    companion object {
        fun getInstance(type_id: Int): StudyChildFragment{
            val fragment = StudyChildFragment()
            val bundle = Bundle()
            bundle.putInt("type_id", type_id)
            fragment.arguments = bundle
            return fragment
        }
    }

    private var type_id = 0

    private val data = arrayListOf<TrainArticleBean>()
    /** 培训列表适配器 */
    private val mTrainingAdapter = StudyArticleListAdapter(data)

    override fun initView(savedInstanceState: Bundle?) {

        type_id = arguments?.getInt("type_id", 0)!!

        binding.apply {
            recyclerView.vertical()
            recyclerView.adapter = mTrainingAdapter
            mTrainingAdapter.setEmptyData()

            refreshLayout.setOnRefreshListener {
                isShowing = false
                p = 1
                vm.getTrainArticleList(type_id, p)
            }

            refreshLayout.setOnLoadMoreListener {
                isShowing = false
                p++
                vm.getTrainArticleList(type_id, p)
            }
        }

        mTrainingAdapter.setOnItemClick { view, position, item ->
            TrainDetailsActivity.launch(
                mActivity,
                1,
                item?.id,
                "${URLConstants.baseUrl}${item?.detail_url}",
            )
        }

    }

    override fun initData() {

    }

    override fun lazyLoadData() {

        p = 1
        vm.getTrainArticleList(type_id, p)

    }

    override fun startObserve() {

        vm.getTrainArticleListData.observeState(this){
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
                binding.refreshLayout.setupEmptyData(data, mTrainingAdapter, p)
            }
            onSuccess {
                dismissLoading()
                binding.refreshLayout.setupData(it?.data, data, mTrainingAdapter, p)
            }
        }

    }

}